package com.yang.crawler.web;


import com.alibaba.fastjson.JSONObject;
import com.yang.crawler.common.Response;
import com.yang.crawler.pdf.config.PdfProperty;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/configuration")
public class ConfigurationController {
    private static final String PDF_CONFIG = "pdf-config.json";

    @GetMapping(value = "/getAllConfig")
    public Response<List<String>> getAllConfig() {
        List<String> configs = new ArrayList<>();
        configs.add(PDF_CONFIG);
        return Response.success(configs);
    }

    @GetMapping(value = "/getConfigText")
    public Response<String> getConfigText(@RequestParam("name") String name) {
        String path = this.getClass().getClassLoader().getResource(name).getPath();
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            return Response.success(stringBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.fail();
    }

    @GetMapping(value = "/pdfConfig")
    public Response<PdfProperty> getPdfConfig() {
        String path = this.getClass().getClassLoader().getResource(PDF_CONFIG).getPath();
        try (FileInputStream inputStream = new FileInputStream(path)) {
            StringBuilder stringBuilder = new StringBuilder();
            byte[] buffer = new byte[4 * 1024];
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                stringBuilder.append(new String(buffer, 0, len));
            }
            return Response.success(JSONObject.parseObject(stringBuilder.toString(), PdfProperty.class));
        } catch (IOException e) {
            e.printStackTrace();
            return Response.fail();
        }
    }

    @PutMapping(value = "/pdfConfig")
    public Response updatePdfConfig(@RequestBody PdfProperty pdfProperty) {
        String jsonString = JSONObject.toJSONString(pdfProperty);
        System.out.println(jsonString);
        String path = this.getClass().getClassLoader().getResource(PDF_CONFIG).getPath();
        try (FileOutputStream outputStream = new FileOutputStream(path)) {
            outputStream.write(jsonString.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Response.success();
    }

}
